package cn.bupt.adt.controller;

import cn.bupt.adt.constant.Constants;
import cn.bupt.adt.entity.autogenerate.DoctorAppUser;
import cn.bupt.adt.entity.autogenerate.OperationType;
import cn.bupt.adt.entity.autogenerate.SubOperationType;
import cn.bupt.adt.model.DoctorModel;
import cn.bupt.adt.model.DoctorSearchModel;
import cn.bupt.adt.service.IDoctorService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/doctorManagement")
public class DoctorController {

    @Autowired
    IDoctorService doctorService;

    @RequestMapping("/index/{pageNum}")
    public ModelAndView doctorIndex(@PathVariable("pageNum") int pageNum, HttpServletRequest request,
                                    DoctorSearchModel doctorSearchModel) {
        System.out.println();
        ModelAndView mv = new ModelAndView(Constants.DOCTOR_INDEX);
        Page<?> page = PageHelper.startPage(pageNum, Constants.PAGESIZE);
        List<DoctorModel> doctors;
        Boolean searchMethod = doctorSearchModel.getSearchMethod();
        if (searchMethod == null) {
            doctors = doctorService.getAllDoctor(request);
        } else {
            if (searchMethod.equals(Constants.BY_NAME)) {
                doctors = doctorService.getDoctorByFuzzyName(doctorSearchModel.getContent());
            } else {
                doctors = doctorService.getDoctorByPhone(doctorSearchModel.getContent());
            }
            mv.addObject("searchMethod", searchMethod);
            mv.addObject("content", doctorSearchModel.getContent());
        }
        mv.addObject("currentPage", page.getPageNum());
        mv.addObject("allPages", page.getPages());
        mv.addObject("doctors", doctors);
        return mv;
    }

    @RequestMapping("/modifypasswd_index/{pageNum}")
    public ModelAndView modifypasswdIndex(@PathVariable("pageNum") int pageNum, HttpServletRequest request,
                                          DoctorSearchModel doctorSearchModel) {
        ModelAndView mv = new ModelAndView(Constants.DOCTOR_MODIFY_PASSWD_INDEX);
        Page<?> page = PageHelper.startPage(pageNum, Constants.PAGESIZE);
        List<DoctorModel> doctors;
        Boolean searchMethod = doctorSearchModel.getSearchMethod();
        if (searchMethod == null) {
            doctors = doctorService.getAllDoctor(request);
        } else {
            if (searchMethod.equals(Constants.BY_NAME)) {
                doctors = doctorService.getDoctorByFuzzyName(doctorSearchModel.getContent());
            } else {
                doctors = doctorService.getDoctorByPhone(doctorSearchModel.getContent());
            }
            mv.addObject("searchMethod", searchMethod);
            mv.addObject("content", doctorSearchModel.getContent());
        }
        mv.addObject("currentPage", page.getPageNum());
        mv.addObject("allPages", page.getPages());
        mv.addObject("doctors", doctors);
        return mv;
    }

    @RequestMapping("/modify_doctor_paswd/{id}")
    public ModelAndView modifyDoctorPasswd(@PathVariable("id") int id) {
        ModelAndView mv = new ModelAndView("forward:/doctorManagement/modifypasswd_index/1");
        String oper_message;
        if (doctorService.resetDoctorPasswdById(id))
            oper_message = "重置密码成功！";
        else
            oper_message = "重置密码失败！";
        mv.addObject("oper_message", oper_message);
        return mv;
    }

    @RequestMapping("/unreviewIndex/{pageNum}")
    public ModelAndView unreviewIndex(@PathVariable("pageNum") int pageNum, HttpServletRequest request,
                                      DoctorSearchModel doctorSearchModel) {
        ModelAndView mv = new ModelAndView(Constants.UNREVIEW_DOCTOR_INDEX);
        Page<?> page = PageHelper.startPage(pageNum, Constants.PAGESIZE);
        List<DoctorModel> doctors;
        System.out.println("se：" + doctorSearchModel.getSearchMethod());
        if (doctorSearchModel.getSearchMethod() == null) {
            doctors = doctorService.getUnreviewDoctor(request);
        } else {
            if (doctorSearchModel.getSearchMethod().equals(Constants.BY_NAME)) {
                doctors = doctorService.getUnreviewDoctorByFuzzyName(doctorSearchModel.getContent());
            } else {
                doctors = doctorService.getUnreviewDoctorByPhone(doctorSearchModel.getContent());
            }
            mv.addObject("searchMethod", doctorSearchModel.getSearchMethod());
            mv.addObject("content", doctorSearchModel.getContent());
        }
        mv.addObject("currentPage", page.getPageNum());
        mv.addObject("allPages", page.getPages());
        mv.addObject("doctors", doctors);
        return mv;
    }

    @RequestMapping("/reviewIndex/{pageNum}")
    public ModelAndView reviewIndex(@PathVariable("pageNum") int pageNum, HttpServletRequest request,
                                    DoctorSearchModel doctorSearchModel) {
        ModelAndView mv = new ModelAndView(Constants.REVIEWED_DOCTOR_INDEX);
        Page<?> page = PageHelper.startPage(pageNum, Constants.PAGESIZE);
        List<DoctorModel> doctors;
        System.out.println("se：" + doctorSearchModel.getSearchMethod());
        if (doctorSearchModel.getSearchMethod() == null) {
            doctors = doctorService.getReviewDoctor(request);
        } else {
            if (doctorSearchModel.getSearchMethod().equals(Constants.BY_NAME)) {
                doctors = doctorService.getReviewDoctorByFuzzyName(doctorSearchModel.getContent());
                System.out.println(doctors.size());
            } else {
                doctors = doctorService.getReviewDoctorByPhone(doctorSearchModel.getContent());
            }
            mv.addObject("searchMethod", doctorSearchModel.getSearchMethod());
            mv.addObject("content", doctorSearchModel.getContent());
        }
        mv.addObject("currentPage", page.getPageNum());
        mv.addObject("allPages", page.getPages());
        mv.addObject("doctors", doctors);
        return mv;
    }

    @RequestMapping("/addDoctor")
    public ModelAndView addDoctor(DoctorAppUser doctor) {
        ModelAndView mv = new ModelAndView("forward:/doctorManagement/index/1");
        String oper_message;
        if (doctorService.addDoctor(doctor))
            oper_message = "添加医生成功，医生于客户端注册后将显示到列表！";
        else
            oper_message = "添加医生失败，可能手机号已被使用！";
        mv.addObject("oper_message", oper_message);
        return mv;
    }

    /*@RequestMapping("/addDoctorPost")
    public synchronized ModelAndView addDoctorPost(Doctor doctor,HttpServletRequest request,
            @RequestParam("operationType") int[] operationTypeId) {
        System.out.println(doctor.getDegree());
        ModelAndView mv = new ModelAndView("forward:/doctorManagement/index/1");
        String oper_message = null;
        if(doctorService.addDoctor(doctor,request,operationTypeId))
            oper_message = "添加医生成功！";
        else
            oper_message = "添加医生失败！";
        mv.addObject("oper_message", oper_message);
        return mv;
    }*/
    @RequestMapping("/operationType/{pageNum}")
    public ModelAndView operationType(@PathVariable("pageNum") int pageNum) {
        ModelAndView mv = new ModelAndView(Constants.OPERATION_TYPE_INDEX);
        Page<?> page = PageHelper.startPage(pageNum, Constants.PAGESIZE);
        mv.addObject("operationTypes", doctorService.getAllOpertionType());
        mv.addObject("currentPage", page.getPageNum());
        mv.addObject("allPages", page.getPages());
        return mv;
    }

    @RequestMapping("/addOperationType")
    public ModelAndView addOperationType(OperationType type) {
        System.out.println(type.getFlag());
        ModelAndView mv = new ModelAndView("forward:/doctorManagement/operationType/1");
        String oper_message;
        if (doctorService.addOperationType(type))
            oper_message = "添加手术类型成功！";
        else
            oper_message = "添加手术类型失败！";
        mv.addObject("oper_message", oper_message);
        return mv;
    }

    @RequestMapping("/deleteOperationType/{id}")
    public ModelAndView deleteOperationType(@PathVariable("id") int id) {
        ModelAndView mv = new ModelAndView("forward:/doctorManagement/operationType/1");
        String oper_message;
        if (doctorService.deleteOperationTypeById(id))
            oper_message = "删除手术类型成功！";
        else
            oper_message = "删除手术类型失败！";
        mv.addObject("oper_message", oper_message);
        return mv;
    }

    @RequestMapping("/deleteSubOperationType/{id}")
    public ModelAndView deleteSubOperationType(@PathVariable("id") int id, String parentId) {
        ModelAndView mv = new ModelAndView("forward:/doctorManagement/subOperationType/" + parentId + "/1");
        String oper_message;
        if (doctorService.deleteSubOperationTypeById(id))
            oper_message = "删除二级手术类型成功！";
        else
            oper_message = "删除二级手术类型失败！";
        mv.addObject("oper_message", oper_message);
        return mv;
    }

    @RequestMapping("/subOperationType/{parentId}/{pageNum}")
    public ModelAndView subOperationType(@PathVariable("parentId") int parentId, @PathVariable("pageNum") int pageNum) {
        ModelAndView mv = new ModelAndView(Constants.SUB_OPERATION_TYPE);
        Page<?> page = PageHelper.startPage(pageNum, Constants.PAGESIZE);
        mv.addObject("subOperationTypes", doctorService.getSubOperationTypeByParentId(parentId));
        mv.addObject("currentPage", page.getPageNum());
        mv.addObject("allPages", page.getPages());
        mv.addObject("parentId", parentId);
        OperationType operationType = doctorService.getOperationTypeById(parentId);
        mv.addObject("parentName", operationType != null ? operationType.getOperationTypeName() : "");
        return mv;
    }

    @RequestMapping("/addSubOperationType")
    public ModelAndView addSubOperationType(@Valid SubOperationType subOperationType, BindingResult bindingResult) {
        ModelAndView mv = new ModelAndView("forward:/doctorManagement/subOperationType/" + subOperationType.getParentId() + "/1");
        String oper_message;
        if (bindingResult.hasErrors()) {
            return mv.addObject("oper_message", bindingResult.getAllErrors().iterator().next().getDefaultMessage());
        }
        if (doctorService.addSubOperationType(subOperationType))
            oper_message = "添加二级手术类型成功！";
        else
            oper_message = "删除手术类型失败！";
        mv.addObject("oper_message", oper_message);
        return mv;
    }

    /*	@RequestMapping("/editPhone")
        public ModelAndView editPhone(Doctor doc) {
            System.out.println(doc.getId());
            System.out.println(doc.getPhone());
            ModelAndView mv = new ModelAndView("forward:/doctorManagement/index/1");
            String oper_message = null;
            if(doctorService.modifyDoctor(doc))
                oper_message = "修改电话成功！";
            else
                oper_message = "修改电话失败！可能是网络原因，也可能是已存在相同的电话，请检查";
            mv.addObject("oper_message", oper_message);
            return mv;
        }*/
    @RequestMapping("/deleteDoctor/{id}")
    public ModelAndView deleteDoctor(@PathVariable("id") int id) {
        ModelAndView mv = new ModelAndView("forward:/doctorManagement/index/1");
        String oper_message;
        if (doctorService.deleteDoctorById(id))
            oper_message = "删除医生成功！";
        else
            oper_message = "删除医生失败！";
        mv.addObject("oper_message", oper_message);
        return mv;
    }

    @RequestMapping("/reviewDoctorDetail/{id}")
    public ModelAndView reviewDoctorDetail(@PathVariable("id") int id) {
        ModelAndView mv = new ModelAndView(Constants.REVIEW_DOCTOR_DETAIL);
        DoctorModel dm = doctorService.getDoctorById(id);
        mv.addObject("item", dm);
        mv.addObject("operationTypes", doctorService.getAllOpertionType());
        return mv;
    }

    @RequestMapping("/doReview/{id}")
    public ModelAndView doReview(@PathVariable("id") int id) {
        ModelAndView mv = new ModelAndView("forward:/doctorManagement/index/1");
        String oper_message;
        if (doctorService.reviewDoctorById(id))
            oper_message = "审核成功！";
        else
            oper_message = "审核失败！";
        mv.addObject("oper_message", oper_message);
        return mv;
    }

    @RequestMapping("/lookupdetail/{id}")
    public ModelAndView lookdetail(@PathVariable("id") int id) {
        ModelAndView mv = new ModelAndView(Constants.DOCTOR_DETAIL);
        DoctorModel dm = doctorService.getDoctorById(id);
        mv.addObject("item", dm);
        mv.addObject("operationTypes", doctorService.getAllOpertionType());
        return mv;
    }

    @RequestMapping("/modifyDoctor")
    public ModelAndView modifyDoctor(HttpServletRequest request, DoctorAppUser doctor,
                                     @RequestParam("operationType") int[] operationType) {
        ModelAndView mv = new ModelAndView("forward:/doctorManagement/lookupdetail/" + doctor.getId());
        String oper_message;
        if (doctorService.modifyDoctor(doctor, request, operationType))
            oper_message = "保存成功！";
        else
            oper_message = "保存失败！";
        mv.addObject("oper_message", oper_message);
        return mv;
    }

    @RequestMapping("/test")
    @ResponseBody
    public Object test(HttpServletRequest request, Integer[] id) {
        MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
        Map<String, Object> a = new HashMap<>();
        List<MultipartFile> appears = req.getFiles("appearance");
        List<MultipartFile> certs = req.getFiles("certification");
        List<MultipartFile> devs = req.getFiles("devices");
        MultipartFile portrait = req.getFile("portr");
        a.put("appear.size is 0:", appears.size() == 0);
        return a;
    }
}
